package org.geektimes.projects.user.validator.bean.validation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;
import java.util.regex.Pattern;

public class PhoneNumberValidAnnotationValidator implements ConstraintValidator<PhoneNumberValid,String> {

    private static final Pattern mobile_pattern = Pattern.compile("1\\d{10}");

    private String message;

    @Override
    public void initialize(PhoneNumberValid annotation) {
        this.message = annotation.message();
    }

    @Override
    public boolean isValid(String phone, ConstraintValidatorContext context) {
        context.disableDefaultConstraintViolation();
        if (Objects.nonNull(phone) && mobile_pattern.matcher(phone).matches()) {
            return true;
        }
        context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
        return false;
    }
}
